package com.imyours.webservice.services;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Session;

import com.imyours.model.team.TeamEntity;
import com.imyours.model.user.UserEntity;
import com.imyours.model.util.HibernateUtil;
import com.imyours.webservice.service.Context;
import com.imyours.webservice.service.ContextService;
import com.imyours.webservice.services.annotation.Service;

@Service(name = "removeFriend")
public class RemoveFriend extends ContextService {

	public RemoveFriend(Context context) {
		super(context);
	}

	public void execute() {
		UserEntity user = getUserEntity();
		if (user != null) {
			long uid = Long.parseLong(context.getParameter().get("userId"));
			long tid = Long.parseLong(context.getParameter().get("teamId"));

			Session se = HibernateUtil.getSessionFactory().openSession();
			TeamEntity teamEntity = (TeamEntity) se.get(TeamEntity.class, tid);
			if (teamEntity != null) {
				if (teamEntity.getUser().getId() == user.getId()) {
					UserEntity tobeDel = null;
					for (UserEntity ue : teamEntity.getUsers()) {
						if (ue.getId() == uid) {
							tobeDel = ue;
							break;
						}
					}
					if (tobeDel != null) {
						teamEntity.getUsers().remove(tobeDel);
						se.beginTransaction();
						se.update(teamEntity);
						se.getTransaction().commit();
						se.close();
					}

					Map<String, String> userMap = null;
					HashMap<String, Object> teamMap = new HashMap<String, Object>();
					teamMap.put("id", teamEntity.getId());
					teamMap.put("name", teamEntity.getName());
					teamMap.put("order", teamEntity.getOrder());
					logger.info("teamName:" + teamEntity.getName());
					List<Map<String, String>> userList = new ArrayList<Map<String, String>>();
					for (UserEntity ue : teamEntity.getUsers()) {
						userMap = new HashMap<String, String>();
						userMap.put("id", "" + ue.getId());
						userMap.put("nickName", ue.getNickname());
						userList.add(userMap);
					}
					teamMap.put("users", userList);
					context.putResult("team", teamMap);
					context.success();
				} else {
					context.fail(4, "no Data");
				}
			} else {
				context.fail(4, "no Data");
			}
		}

	}

}
